import { shareQrCode } from '../../../../api/index'
Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    detail: {
      type: Object,
      value: {}
    }
  },
  data: {
    mall: '',
    qrcode: '',
    poster: '',
    loading: false,
    imagePath: ''
  },
  methods: {
    async createPoster () {
      try {
        wx.showLoading({ title: '加载中' })
        await this.getQrCode()
        // const { path: mall } = await wx.$pro.getImageInfo({ src: 'https://static.chaodp.com/chao_wx_card/share_home.png' })
        // this.setData({ mall: mall })
        wx.hideLoading()
        this.createNewImg()
      } catch (err) {
        wx.hideLoading()
        console.log(err)
      }
    },
    async getQrCode() {
      try {
        // let redirect = `/pages/card/preview/index?id=${this.data.card.uid}&cardId=${this.data.card.id}&userId=${this.data.card.uid}`
        // let scene = encodeURIComponent(`${redirect}`)
        const { ResultSet } = await shareQrCode({ scene: `id=${this.data.detail.Material.id}`, page: 'pages/materialDetail/index', need_img: 1 })
        const { path: qrcodeImg } = await wx.$pro.getImageInfo({ src: ResultSet.userData.qrCode })
        const { path: poster } = await wx.$pro.getImageInfo({ src: ResultSet.userData.img })
        this.setData({ qrcode: qrcodeImg, poster: poster })
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.msg, icon: 'none' })
      }
    },
    rpx (n) {
      return n * wx.getSystemInfoSync().windowWidth / 750
    },
    createNewImg () {
      let that = this
      // 使用 wx.createContext 获取绘图上下文 context
      var context = wx.createCanvasContext('plainId', this) // 创建绘图工具
      let windowWidth = this.rpx(572)
      let windowHeight = this.rpx(866)
      // 背景图
      context.save()
      context.beginPath()
      context.setFillStyle('#fff')
      context.fillRect(0, 0, this.rpx(572), this.rpx(866))
      context.closePath()
      context.stroke()
      context.drawImage(this.data.poster, this.rpx(66), this.rpx(50), this.rpx(440), this.rpx(576))
      // 字体
      context.setFontSize(this.rpx(26))
      context.fillStyle = '#363636'
      context.fillText(`识别小程序码`, this.rpx(50), this.rpx(750))
      context.fillText(`查看商城详情`, this.rpx(370), this.rpx(750))
      context.save()
      // 二维码
      context.restore()
      context.drawImage(this.data.qrcode, (windowWidth - this.rpx(140)) / 2, this.rpx(676), this.rpx(140), this.rpx(140))
      // context.restore()
      // this.drawRoundRect(context, (windowWidth - this.rpx(64)) / 2, this.rpx(788), this.rpx(64), this.rpx(64), this.rpx(32))
      // context.save()
      // context.clip()
      // context.drawImage(this.headPic, (windowWidth - this.rpx(64)) / 2, this.rpx(788), this.rpx(64), this.rpx(64))
      // context.restore()
      context.draw(
        setTimeout(() => {
          wx.canvasToTempFilePath({
            canvasId: 'plainId',
            success: function (res) {
              that.setData({
                imagePath: res.tempFilePath
              })
            }
          }, that)
        }, 500)
      )
      this.setData({
        loading: true
      })
    },
    // createNewImg () {
    //   console.log(this.data)
    //   // 使用 wx.createContext 获取绘图上下文 context
    //   var context = wx.createCanvasContext('plainId', this) // 创建绘图工具
    //   // 背景图
    //   let that = this
    //   context.save()
    //   this.roundRect(context, 0, 0, this.rpx(690), this.rpx(783), this.rpx(20))
    //   context.setFontSize(this.rpx(40))
    //   context.font = 'bold'
    //   context.fillStyle = '#060606'
    //   context.textAlign = 'center'
    //   context.fillText(`识别小程序码`, this.rpx(345), this.rpx(120))
    //   context.setFontSize(this.rpx(24))
    //   context.fillText(`识别小程序码`, this.rpx(345), this.rpx(160))
    //   context.setFontSize(this.rpx(28))
    //   context.fillStyle = '#211E1B'
    //   context.fillText(`查看商城详情`, this.rpx(345), this.rpx(725))
    //   context.drawImage(this.data.poster, this.rpx(345) - context.measureText(this.data.card.user_company).width - this.rpx(10), this.rpx(699), this.rpx(30), this.rpx(30))
    //   context.drawImage(this.data.qrcode, this.rpx(124), this.rpx(202), this.rpx(441), this.rpx(441))
    //   context.draw(
    //     setTimeout(() => {
    //       wx.canvasToTempFilePath({
    //         canvasId: 'plainId',
    //         success: function (res) {
    //           that.setData({
    //             imagePath: res.tempFilePath
    //           })
    //         }
    //       }, that)
    //     }, 500)
    //   )
    //   this.setData({
    //     loading: true
    //   })
    // },
    async save() {
      const { authSetting } = await wx.$pro.getSetting()
      if (authSetting['scope.writePhotosAlbum'] === undefined) {
        const { errMsg } = await wx.$pro.authorize({ scope: 'scope.writePhotosAlbum' })
        if (errMsg === 'authorize:ok') {
          const { path: imagePath } = await wx.$pro.getImageInfo({ src: this.data.imagePath })
          await wx.saveImageToPhotosAlbum({ filePath: imagePath })
          wx.showToast({ title: '图片已保存到相册，快去分享吧', icon: 'none' })
        }
      } else if (authSetting['scope.writePhotosAlbum'] === false) {
        const { authSetting } = await wx.$pro.openSetting()
        if (authSetting['scope.writePhotosAlbum']) this.save()
      } else {
        const { path: imagePath } = await wx.$pro.getImageInfo({ src: this.data.imagePath })
        await wx.saveImageToPhotosAlbum({ filePath: imagePath })
        wx.showToast({ title: '图片已保存到相册，快去分享吧', icon: 'none' })
      }
    },
    roundRect(ctx, x, y, w, h, r, c = '#fff') {
      if (w < 2 * r) { r = w / 2; }
      if (h < 2 * r) { r = h / 2; }
   
      ctx.beginPath()
      ctx.fillStyle = c
   
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
      ctx.moveTo(x + r, y)
      ctx.lineTo(x + w - r, y)
      ctx.lineTo(x + w, y + r)
   
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
      ctx.lineTo(x + w, y + h - r)
      ctx.lineTo(x + w - r, y + h)
   
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
      ctx.lineTo(x + r, y + h)
      ctx.lineTo(x, y + h - r)
   
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
      ctx.lineTo(x, y + r)
      ctx.lineTo(x + r, y)
   
      ctx.fill()
      ctx.closePath()
    },
    
    
    drawText(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
      let count = ctx.measureText(str).width / canvasWidth
      if (count >= 2) {
        let allRow = Math.ceil(ctx.measureText(str).width / canvasWidth) // 实际总共能分多少行
        let maxRow = 2
        if (allRow < maxRow) {
          ctx.fillText(str, leftWidth, initHeight) // 绘制截取部分
        } else {
          let rowWidth = 0
          let row = 0
          let breakIndex = 0
          for (let i = 0; i < str.length && row < maxRow; i++) {
            rowWidth += ctx.measureText(str[i]).width
            if (rowWidth > canvasWidth) {
              rowWidth = 0
              row++
              if (row >= maxRow) ctx.fillText(str.slice(breakIndex, i - 2) + '...', leftWidth, initHeight + 20)
              else {
                breakIndex = i
                ctx.fillText(str.slice(0, i), leftWidth, initHeight) // 绘制截取部分
              }
            }
          }
        }
      } else {
        let lastSubStrIndex = 0 // 每次开始截取的字符串的索引
        let lineWidth = 0
        for (let i = 0; i < str.length; i++) {
          lineWidth += ctx.measureText(str[i]).width
          if (lineWidth > canvasWidth) {
            ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight) // 绘制截取部分
            initHeight += 25 // 16为字体的高度
            lineWidth = 0
            lastSubStrIndex = i
            titleHeight += 30
          }
          if (i === str.length - 1) { // 绘制剩余部分
            ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight)
          }
        }
      }
    },
    drawRoundRect (cxt, x, y, width, height, radius) {
      cxt.beginPath()
      cxt.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2)
      cxt.lineTo(width - radius + x, y)
      cxt.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2)
      cxt.lineTo(width + x, height + y - radius)
      cxt.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2)
      cxt.lineTo(radius + x, height + y)
      cxt.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI)
      cxt.lineTo(x, y)
      cxt.closePath()
    },
    close() {
      this.triggerEvent('close')
    }
  },
  observers: {
    'show': function(val) {
      if (val) this.createPoster()
    },
  },
})